<template>
  <div class="Home">
    <div id="navigator_top">
      <div class="navigator-top-buttons-container">
        <button type="button" class="navigator-top-button">首页</button>
        <button type="button" class="navigator-top-button" @click="search">搜索</button>
        <input class="search-input" placeholder="在主页面中搜索" type="text" v-model="keywords" @keyup.enter="search"/>
      </div>
      <div class="avatar-container">
        <img id="userAvatar" v-bind:src="userAvatar" alt="用户头像" @click="toUserpage()"/>
      </div>
    </div>
    <div class="content" id="main" style="height: fit-content;">
      <div class="goods-container" v-for="(item, index) in data" :key="index">
        <div class="folding-goods" @click="jumpDetail(item.pid)">
          <img class="folding-img" :src="item.pimgLink"/>
          <div class="folding-title" v-html="item.pdec"></div>
          <div class="folding-price">{{ item.pprice}}元</div>
        </div>
      </div>
    </div>
    <!--<div style="font-size: larger;" @click="jumpDetail($event)"> check </div>-->
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'Home',
  data() {
    return {
      originData: [],
      data: [], // require('@/assets/' + 'preview.json')
      // userLink: '', // to-do 用户详情页链接
      userAvatar: '',
      keywords: ''
    }
  },
  methods: {
    create_goods() {
      var self = this
      let url = this.globalData.apiURL + '/product/preview'
      axios.get(url).then((res) => {
        if(res.status === 200){
          self.data = res.data
        } else {
          if(window.confirm(String(res) + '\n\n请求' + url + '出错了，开始展示假数据！')){
            self.data = require('@/assets/' + 'preview.json')
          } else {
            self.data = [{pid: '', pdec: '出错了！', pprice: '', pimgLink: ''}]
          }
        }
      }, (err) => {
        /* to-do 报错信息 */
        if(window.confirm(String(err) + '\n\n请求' + url + '出错了，开始展示假数据！')){
          self.data = require('@/assets/' + 'preview.json')
        } else {
          self.data = [{pid: '', pdec: '出错了！', pprice: '', pimgLink: ''}]
        }
      }).then(() => {
        this.originData = JSON.parse(JSON.stringify(this.data))
      })
    },
    jumpDetail(pid){
      // this.$router.push({name: 'Detail', query: {pid: pid}});
      window.open('./detail?pid=' + pid)
    },
    toUserpage() {
      if(this.globalData.User.Id === -1){
        // 跳转到登录页
        this.$router.push({name: 'Connect'})
      } else {
        /* to-do 跳转到用户详情页 */
        this.$router.push({name: 'UserInfo'})
        console.log('pretend to jump to link xxx')
      }
    },
    search() {
      // 根据keywords执行搜索程序
      if(/\S/.test(this.keywords)){
        let reg = new RegExp(this.keywords.trim().replace(/\s+/g, '|'), 'i')
        this.data = JSON.parse(JSON.stringify(this.originData.filter((item) => {
          return reg.test(item.pdec)
        })))
        for(let i = 0; i < this.data.length; ++i) {
          this.data[i].pdec = this.hightLight(this.data[i].pdec)
        }
      }
    },
    hightLight(str) {
      const reg = new RegExp(this.keywords.replace(/\s+/g, '|'), 'ig')
      return str.replace(reg, (val) => {
        return `<span style="color: red;">${val}</span>`
      })
    }
  },
  beforeMount() {
    this.create_goods()
    // console.log('autoLoading')
    // console.log('Storage', localStorage.getItem('User'))
    // this.globalData.User.loadInfo()
    if(localStorage.getItem('UserJSON') !== null){
      console.log('autoload success', localStorage.getItem('UserJSON'))
      this.globalData.User = JSON.parse(localStorage.getItem('UserJSON'))
    }
    if(this.globalData.User.Id === -1) {
      console.log('autoload', 'needLogin')
      // 未登录时
      this.userAvatar = require('@/assets/' + 'no-login.jpg')
    } else if(this.globalData.User.User_pic === '') {
      // 未设置头像时
      this.userAvatar = require('@/assets/' + 'no-avatar.jpg')
    } else {
      this.userAvatar = this.globalData.User.User_pic
    }
  }
}
</script>

<style scoped>

/* 顶部导航栏 */
#navigator_top {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 50px;
    background-image: linear-gradient(to bottom, #2c7dbdb0, #2c7dbd70);
    /*background-color: rgb(92, 173, 213, 0.8);*/
    z-index: 100;
}

.avatar-container {
  width: 50px;
  height: 50px;
  float: right;
  margin-right: 15px;
  border-radius: 25px; /* 令头像图片呈圆形 */
  overflow: hidden;
}

/* 外部用户头像 */
#userAvatar {
  margin:0;
  padding: 0;
  object-fit: cover; /* 令图片居中展示 */
  width: 50px;
}
/* .avatar-container:hover {
    border-radius: 15px;
    transition: 0.6s linear;
} */

.content {
    display: flex;
    flex-wrap: wrap;    /* 令子元素居中 */
    justify-content: center;
    margin-top: 50px;
    margin-bottom: 20px; /* 确保内容不被导航栏遮挡 */
}

/* 商品格 */
.goods-container {
    margin: 2px;
    height: 358px;
    width: 240px;
    float: left;
}

/* 商品格内容 */
.folding-goods {
    border-radius: 12px;
    /*box-sizing: border-box;*/
    border: 3px solid transparent;
    cursor: pointer;
    height: 342px;
    width: 224px;
    margin: 8px 8px 8px 8px;
    position: relative;
}

/* */
.folding-goods:hover {
    border: 3px solid rgb(175, 47, 8);
    /*padding: 1px;*/
    transition: all .3s;
}

/* 商品大图 */
.folding-img {
    clear: both;
    display: block;
    margin: auto;
    border-radius: 12px;
    width: 210px;   /* 略小于上级div宽度 */
    overflow: hidden;
    position: relative;
}

/* 商品标题 */
.folding-title {
    text-align: left;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    line-clamp: 4;
    overflow: hidden;
}

.folding-price {
  text-align: center;
  position: absolute;
  width: 100%;
  bottom: 0;
  margin-bottom: 15px;
  font-size: large;
  font-style: italic;
  font-weight: bolder;
  color: #ff5000;
}
.navigator-top-buttons-container {
  float: left;
  width: 50%;
  height: 100%;
  margin: auto;
  text-align: left;
}

.navigator-top-button {
  display: inline;
  left: 30px;
  width: 60px;
  height: 40px;
  position: relative;
  top: 5px;
  background-color: rgba(4, 6, 92, 0.714);
  color: aliceblue;
}

.search-input {
  display: inline;
  position: absolute;
  top: 15px;
  left: 220px;
}

</style>
